package com.luoran.bartalks.core;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.luoran.bartalks.action.vo.UserMenuVo;
import com.luoran.bartalks.entity.biz.UserInfo;
import com.luoran.bartalks.service.IUserService;
import com.luoran.bartalks.utils.Constant;
import com.luoran.bartalks.utils.MD5;

/**
 * @author lifetime
 *
 */
@Controller
@RequestMapping("/user")
public class LoginAction {

	@Autowired
	private IUserService userService;

	@RequestMapping("/login")
	public String index(@RequestParam(required = false) String redirectURL, Model model) {
		model.addAttribute("redirectURL", redirectURL);
		return "/login/login-in";
	}

	@RequestMapping("/fail")
	public String fail(@RequestParam(required = false) String redirectURL, Model model) {
		model.addAttribute("redirectURL", redirectURL);
		model.addAttribute("msg", "用户名或密码错误");
		return "/login/login-fail";
	}
	
	@RequestMapping(value = "/login/auth", method = RequestMethod.GET)
	public String login() {
		return "/user/login";
	}
	
	@RequestMapping(value = "/login/auth", method = RequestMethod.POST)
	public String login(@RequestParam String number, @RequestParam String pwd, @RequestParam(required = false) String redirectURL, HttpServletResponse response,HttpServletRequest request) {
		UserInfo info = userService.getUser(number, MD5.get(pwd));
		if (info == null) {
			if (StringUtils.isEmpty(redirectURL)) {
				return "redirect:/user/fail";
			}
			try {
				return "redirect:/user/fail?redirectURL=" + URLEncoder.encode(redirectURL, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				return "redirect:/user/fail";
			}
		}
		String accessToken = SessionManager.put(number, info,swapMenuWithPath(userService.getUserMenus(info.getId()),request.getContextPath()));
		Cookie cookie = new Cookie(Constant.UserNumber, number);
		cookie.setPath("/");
		response.addCookie(cookie);
		cookie = new Cookie(Constant.AccessToken, accessToken);
		cookie.setPath("/");
		response.addCookie(cookie);
		UserContext.init(SessionManager.get(number));
		if (StringUtils.isEmpty(redirectURL)) {
			return "redirect:/workbench";
		} else {
			return "redirect:" + redirectURL;
		}
	}
	
	protected List<UserMenuVo> swapMenuWithPath(List<UserMenuVo> menus,String ctxPath) {
			for (UserMenuVo menu : menus) {
				if(!StringUtils.isEmpty(menu.getUrl())) {
					if(menu.getUrl().startsWith("/")) {
						menu.setUrl(ctxPath + menu.getUrl());
					}else {
						menu.setUrl(ctxPath + "/" +menu.getUrl());
					}
				}
				if(menu.getChilds().size() != 0) {
					for (UserMenuVo child : menu.getChilds()) {
						if(!StringUtils.isEmpty(child.getUrl())) {
							if(child.getUrl().startsWith("/")) {
								child.setUrl(ctxPath + child.getUrl());
						}else {
								child.setUrl(ctxPath + "/" +child.getUrl());
							}
						}
					}
				}
			}
			return menus;
			}
	
	@RequestMapping("/logout")
	public String logout(@CookieValue(value=Constant.UserNumber,required=false) String number,@CookieValue(value=Constant.AccessToken,required=false) String accessToken){
		if(SessionManager.isValid(number, accessToken)){
			SessionManager.clear(number);
			return "redirect:/";
		}
		return "redirect:/user/fail";
	}

}
